import { auth } from '@/lib/auth';
import env from '@/lib/env';
import redis, { genInChatKey } from '@/lib/redis';
import { socketsMap } from '@/lib/socket';
import type { NextRequest } from 'next/server';
import { Server } from 'socket.io';

export async function POST(request: NextRequest) {
  try {
    if (request.headers.get('Auth') !== env.BETTER_AUTH_SECRET)
      throw new Error('未认证');
    const port = new URL(env.SOCKET_URL).port;
    const io = new Server(Number.parseInt(port), {
      addTrailingSlash: false,
    });
    io.on('connection', async (socket) => {
      const headers = new Headers();
      headers.set('cookie', socket.handshake.headers.cookie || '');
      const session = await auth.api.getSession({
        headers,
      });
      if (!session) socket.disconnect();
      else {
        const userId = session.user.id;
        const sockets = socketsMap.get(userId) || [];
        sockets.push(socket);
        socketsMap.set(userId, sockets);

        socket.on('disconnect', async () => {
          const sockets = (socketsMap.get(userId) || []).filter(
            (s) => s.id !== socket.id,
          );
          sockets.length
            ? socketsMap.set(userId, sockets)
            : socketsMap.delete(userId);

          if (session.user.role === 'shop') {
            const keys = await redis.keys(
              genInChatKey({
                userId: '*',
                shopUserId: userId,
              }),
            );
            await redis.del(keys);
          }
        });
      }
    });
    return new Response('init complete');
  } catch (error: any) {
    console.error(error);
    return new Response(error.message ?? 'internal server error');
  }
}
